package com.drug.mingkang.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drug.mingkang.permission.model.PerModule;
import com.drug.mingkang.permission.model.TreeNode;
import com.drug.mingkang.permission.service.PerModuleService;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * 描述:工具类
 *
 * @author 文昌剑
 * @version 1.0
 * @date 2020/7/19 13:03
 */
@Component
public class Tools {

    /**
     * 发送json需要用到的对象
     */
    private static final Gson gson = new Gson();

    @Resource
    private PerModuleService perModuleService;

    public  Map<String,Object> limit(List list, Integer count){
        Map<String,Object> map = new HashMap<>();
        map.put("data", list);
        map.put("count", count);
        map.put("msg","");
        map.put("code",0);
        return map;
    }

    /**
     * 写入图片
     *
     * @param userFile  传入的图片
     * @return
     * @throws IOException
     */
    public String writeImg(MultipartFile userFile, String url) throws IOException {
        System.out.println("url = " + url);
        String name =userFile.getOriginalFilename();//得到原文件名
        //获取后缀名
        String suffixName = name.substring(name.lastIndexOf("."));
        //生成uuid
        String uuid = UUID.randomUUID().toString();
        //拼接
        String fileName = uuid+suffixName;
        //保存文件
        userFile.transferTo(new File(url+"//"+fileName));
        System.out.println("fileName = " + fileName);
        return fileName+"&"+uuid;
    }



    /**
     * 遍历list下的所有子节点
     * @param list
     * @return
     */
    public List<TreeNode> getTreeByUserId(List<PerModule> list){
        List<TreeNode> list1 = new ArrayList<TreeNode>(1);
        for (PerModule perModule : list) {
            if("max".equals(perModule.getModModuleId())){
                TreeNode treeNode = new TreeNode();
                treeNode.setId(perModule.getModuleId());
                treeNode.setName(perModule.getModuleName());//没有复选
                treeNode.setLabel(perModule.getModuleName());//复选
                list1.add(findChildren(treeNode,list));
            }
        }
        return list1;
    }

    /**
     * 寻找子节点
     * @param treeNode
     * @param list
     * @return
     */
    public TreeNode findChildren(TreeNode treeNode , List<PerModule> list){
        for (PerModule moduleTree : list) {
            if(treeNode.getId().equals(moduleTree.getModModuleId())){
                if(treeNode.getChildren()==null){
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                TreeNode treeNode1 = new TreeNode();
                treeNode1.setId(moduleTree.getModuleId());
                //没有复选
                treeNode1.setName(moduleTree.getModuleName());
                //复选
                treeNode1.setLabel(moduleTree.getModuleName());
                treeNode.getChildren().add(findChildren(treeNode1, list));
            }
        }
        return treeNode;
    }


    /**
     * 递归树方法
     * @param modMId 模块id
     * @return
     */
    public List<TreeNode> returnTree(String modMId) {
        List<PerModule> listRoot = perModuleService.selectParent(modMId);
        List<TreeNode> listTree = new ArrayList<>(1);
        for (PerModule mod : listRoot) {
            List<TreeNode> treeNodes = this.returnTree(mod.getModuleId());
            TreeNode treeNode = new TreeNode();
            treeNode.setId(mod.getModuleId());
            treeNode.setName(mod.getModuleName());//没有复选
            treeNode.setLabel(mod.getModuleName());//复选
            //为了消除children[]
            if(treeNodes.size()==0){
                treeNode.setChildren(null);
            }else{
                treeNode.setChildren(treeNodes);
            }
            listTree.add(treeNode);
        }
        return listTree;
    }


    /**
     * JSON 转 POJO
     */
    public  <T> T getObject(String pojo, Class<T> tclass) {
        try {
            return JSONObject.parseObject(pojo, tclass);
        } catch (Exception e) {
            System.err.println(tclass + "转 JSON 失败");
        }
        return null;
    }

    /**
     * POJO 转 JSON
     */
    public  <T> String getJson(T tResponse){
        String pojo = JSONObject.toJSONString(tResponse);
        return pojo;
    }

    /**
     * List<T> 转 json 保存到数据库
     */
    public  <T> String listToJson(List<T> ts) {
        String jsons = JSON.toJSONString(ts);
        return jsons;
    }

    /**
     * json 转 List<T>
     */
    public  <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
        return ts;
    }





    /**
     *
     * @param accepter 接收者
     * @param Mes   信息
     * @return
     */
    public static int sendMail(String accepter, String Mes) {
        Properties prop = new Properties();
        //需要发送的邮件服务器
        prop.setProperty("mail.host","smtp.qq.com");
        //邮件发送协议smtp，不知道的请自行百度，如果实在不懂也没用关系，只需要按照这个写
        prop.setProperty("mail.transport.protocol","smtp");
        //QQ邮箱的SSL安全验证
        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        prop.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);

        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        //QQ邮箱端口号
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.socketFactory.port","465");
        prop.put("mail.smtp.ssl.enable", "true");
        //设置smtp授权，true标识允许
        prop.setProperty("mail.smtp.auth","true");
        //接下来开始正式写发送邮件代码。
        //首先需要创建session,此session表示邮件里面的会话。javax.mail.Session
        Session session = Session.getInstance(prop);
        //2、通过session得到transport对象,这个对象是专门用来发送邮件的对象
        try {
            Transport trans = session.getTransport();
            //3、提供用户名和密码hcxjwnoniqskddce
            trans.connect("smtp.qq.com","2357248777", "tqusuzcbdlqreace") ;
            //4、创建邮件
            Message msg = new MimeMessage(session) ;

            //发送者
            msg.setFrom(new InternetAddress("2357248777@qq.com")) ;
            //接收者
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(accepter)) ;
            msg.setSubject("幸运商城");
            msg.setContent(Mes,"text/html;charset=UTF-8");//正文
            //5、发送邮件
            trans.sendMessage(msg,msg.getAllRecipients());
            //6、关闭发送对象
            trans.close();
            System.out.println("邮件发送完成！！！");
            return 1;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return 0;
    }






    /**
     * 	首字母大写
     * @param word 所要变大写的内容
     * @return
     */
    public static String firstUp(String word) {
        String s = word.substring(1);
       // System.out.println("s = " + s);
        if(word==null){
            return "";
        }
        //方法未实现
        return word.substring(0,1).toUpperCase()+word.substring(1);
    }




    /**
     * Map通过value找Key
     * @param map
     * @param value
     * @return
     */
    public static Object getKey(Map map, Object value){
        List<Object> keyList = new ArrayList<>();
        for(Object key: map.keySet()){
            if(map.get(key).equals(value)){
                keyList.add(key);
            }
        }
        return keyList;
    }
    /**
     * 提供字符串判断是否为空
     * @param input
     * @return input为空返回true
     */
    public static boolean isEmpty(String input){
        return null==input || 0==input.length() || 0==input.replaceAll("\\s", "").length();
    }
}
